package com.cea.papyrus.diagram.statemachine.editpart;

import java.util.Iterator;

import org.eclipse.gef.commands.Command;
import org.eclipse.gef.commands.CompoundCommand;

import com.cea.papyrus.core.commands.connection.GraphEdgeDeleteCommand;
import com.cea.papyrus.core.commands.factories.DiagramElementDeleteCommandFactory;
import com.cea.papyrus.core.editor.ModelManager;
import com.cea.papyrus.core.editpart.GraphNodeWithSemanticEditPolicy;
import com.cea.papyrus.diagram.statemachine.command.DeleteRegionNodeCommand;
import com.cea.papyrus.diagram.statemachine.command.UMLDi2ElementDeleteFactory;
import com.cea.papyrus.diagraminterchange2.di2.GraphConnector;
import com.cea.papyrus.diagraminterchange2.di2.GraphEdge;
import com.cea.papyrus.diagraminterchange2.di2.GraphElement;
import com.cea.papyrus.diagraminterchange2.di2.GraphNode;

/**
 * Specific EditPolicy for RegionEditPart to cope with suppression of nodes.
 * 
 * @author David Servat
 * @since 29 jan. 07
 */
public class RegionEditPolicy extends GraphNodeWithSemanticEditPolicy{

	/** The channel. */
	private int channel = 501;    

	/**
	 * The constructor.
	 * @param modelManager the ModelManager
	 */
	public RegionEditPolicy(ModelManager modelManager){
		super(modelManager);
	}
	
    /**
     * Return the delete factory used to return a delete command.
     * This method can be subclassed in order to return a specific factory.
      * @return
     */
	@Override
    protected UMLDi2ElementDeleteFactory getDeleteCommandFactory() {
        return UMLDi2ElementDeleteFactory.eINSTANCE;
    }

	@Override
	protected Command getOrphanCommand() {
		// TODO Auto-generated method stub
		return null;
	}
	/**
	 * Specific processing for Regions, route the call to DeleteRegionNodeCommand.
	 * @param parent GraphElement
	 * @param child GraphNode
	 */
	protected Command getDeleteFromDiagramCommand(GraphElement parent, GraphNode child){
		CompoundCommand command = new CompoundCommand();
		if((child == null) || (parent == null)) {
			throw new IllegalArgumentException("child or parent is null");
		}
		command.add(new DeleteRegionNodeCommand(child));

		// delete all edges from and to this container
		// Walk throw all edges accessible from the node.
		Iterator<GraphConnector> anchors = child.getAnchorage().iterator();
		while (anchors.hasNext()) {
			Iterator<GraphEdge> edges = anchors.next().getGraphEdge().iterator();
			while(edges.hasNext())
			{
				GraphEdge edge = edges.next();
			    command.add(new GraphEdgeDeleteCommand(edge));
			}
		}

//		delete name
		Iterator it=parent.getContained().iterator();
		while (it.hasNext()){
			GraphElement ge=(GraphElement)it.next();
			if ((ge.getSemanticParent()!=null) && ge.getSemanticParent().equals(child)){
			command.add(DiagramElementDeleteCommandFactory.eINSTANCE.createCommand(ge));}
		}

		return command;
	}
}
